Array.prototype.add = function(obj, nodup){
	if (nodup) {
	    this[this.length] = obj;
	}
};
Array.prototype.remove = function(o){
	var i = this.indexOf(o);
	if (i > -1) {
	    this.splice(i, 1);
	}
	return (i > -1);
};

(function(){
    var KUI = window.KUI = function(){
        return new KUI.fn.init(arguments);
    };
	KUI.fn = KUI.prototype = {
		version: '0.9.0',
		init: function(els){			
	        this.elements = this.selector(els[0],els[1]);
			return this;
		},		
		selector:function(args1,arg2){
			if (typeof args1 == "object") {
				var els = [];
				els[0]= args1;
				return els;
			}
			else{	
				return  arg2?mini(args1,arg2):mini(args1);
			}
		},
		size:function(){
			return (this.elements.length);
		},
		val: function(newValue){
            if (this.elements[0])
            {
                if (newValue == undefined) {
					var el = this.elements[0];
					var sType = el.type;
					switch(sType)
				    {
				        case "text":
				        case "hidden":
				        case "password":
				        case "file":
				        case "textarea": return el.value;
						case "checkbox":
				        case "radio": return e.checked;
				        case "select-one":
				        case "select-multiple": return (function(el){
				            for (var i = 0, l = el.options.length; i < l; i++) {
				                if (el.options[i].selected) {
									 return el.options[i].value;
								}
				            }
						})(el);
				    }
				}
				this.elements[0].value = newValue;
                return this; 
            }
        },
		dom: function(){            
            return this.elements[0]?this.elements[0]:this; 
		},
		each: function(fn){
            for (var i = 0, l = this.elements.length; i < l; i++) {
                fn.call(this, this.elements[i]);
            }
            return this;
        },	

		setStyle: function(styleObj) {
			this.each(function(els){               
				 if (typeof(styleObj) == "object") { 
		             for (s in styleObj) { 
		                 var cssArrt = s.split("-"); 
		                 for (var i = 1; i < cssArrt.length; i++) { 
		                     cssArrt[i] = cssArrt[i].replace(cssArrt[i].charAt(0), cssArrt[i].charAt(0).toUpperCase()); 
		                 } 
		                 var cssArrtnew = cssArrt.join(""); 
		                 els.style[cssArrtnew] = styleObj[s]; 
		             } 
		         } else if (typeof(styleObj) == "string") { 
		             els.style.cssText = styleObj; 
		         }
            });
			 return this;  
		},
		
	     getStyle: function(styleName) { 
	     	if(styleName)
	         return this.elements[0].style[styleName] ? this.elements[0].style[styleName] : this.elements[0].currentStyle ? this.elements[0].currentStyle[styleName] : window.getComputedStyle(this.elements[0], null)[styleName];
	        else return this.elements[0].style ? this.elements[0].style : this.elements[0].currentStyle ? this.elements[0].currentStyle: window.getComputedStyle(this.elements[0], null);  
	     },
		
		hasClass: function(className) { 
			if (!this.elements[0].className) { 
	         	return false; 
	     	}
			return new RegExp('(\\s|^)' + className + '(\\s|$)').test(this.elements[0].className);           
		},
		
		hasClassName: function(element, className) { 
	         element = this.get(element); 
	         if (!element.className) { 
	             return false; 
	         } 
	         return new RegExp('(\\s|^)' + className + '(\\s|$)').test(element.className); 
	  
	     }, 
		
		addClass: function(className) { 
		     this.each(function(els){  
				 if (!this.hasClass(className)) { 
			        els.className += " " + className; 
			     }
			 });
			 return this; 
		},
		
		setClass: function(className) { 
		     this.each(function(els){
				 if (!this.hasClass(className)) { 
			         els.className = className; 
			     }
			}); 
			return this; 
		},
		 
		getClass: function() { 
		     return this.elements[0].className; 
		},
		 
		removeClass: function(className) { 
		     this.each(function(els){
				 if (this.hasClass(className)) { 
			         els.className = els.className.replace(new RegExp('(\\s|^)' + className + '(\\s|$)'), " "); 
			     } 
			 });
			 return this; 
		},
		
		setOpacity: function(n){
			this.each(function(els){
				 els.style.opacity=n/100; 
				 els.style.filter='alpha(opacity='+n+')';
			 });
			 return this; 
		},
		 
	     bindEvent: function(eventName,fn) { 
	         this.each(function(els){				
				var mouseRouter = new KUI.Event.EventRouter(els, eventName);
				mouseRouter.addListener(fn);
			}); 
			return this;
	     },
		 
	     unbindEvent: function(eventName) { 
	         this.each(function(els){				
				var mouseRouter = new KUI.Event.EventRouter(els, eventName);
				mouseRouter.removeListener(fn);
			}); 
			return this;
	     },
		 
	     onclick: function(fn) { 
	         this.each(function(els){				
				this.bindEvent('onclick',fn);
			}); 
	     },
		 
	     getSize: function() {	          
	         if (this.getStyle("display") != "none") { 
	             return { width: this.elements[0].offsetWidth || parseInt(this.getStyle("width")), height: this.elements[0].offsetHeight || parseInt(this.getStyle("height"))}; 
	         } 
	         var _addCss = { display: "", position: "absolute", visibility: 'hidden' }; 
	         var _oldCss = {}; 
	         for (i in _addCss) { 
	             _oldCss[i] = this.getStyle(i); 
	             this.setStyle(_addCss); 
	         } 
	         var _width = this.elements[0].clientWidth || parseInt(this.getStyle("width")); 
	         var _height = this.elements[0].clientHeight || parseInt(this.getStyle("height")); 
	         for (i in _oldCss) { 
	             this.setStyle(_oldCss); 
	         } 
	         return { width: _width, height: _height }; 
	     },
		 
	     getPos: function() { 
		 	 var el = this.elements[0];
//	         return document.documentElement.getBoundingClientRect && (function() {
//	             var el = els;
//				 var pos = el.getBoundingClientRect(); 
//	             return { x: pos.left + document.documentElement.scrollLeft, y: pos.top + document.documentElement.scrollTop }; 
//	         })() || (function() { 
//	             var _x = 0, _y = 0; 
//	             do { 
//	                 _x += el.offsetLeft; 
//	                 _y += el.offsetTop; 
//	             } while (el = el.offsetParent); 
//	             return { x: _x, y: _y }; 
//	         })(); 
			var ua = navigator.userAgent.toLowerCase();
			if (el.parentNode === null || el.style.display == 'none') {
			    return false;
			}
			var parent = null;
			var pos = [];
			var box;
			if (el.getBoundingClientRect) //IE
			{
			    box = el.getBoundingClientRect();
			    var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
			    var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
			    return {
			        x: box.left + scrollLeft,
			        y: box.top + scrollTop
			    };
			}
			else 
			    if (document.getBoxObjectFor) // gecko    
			    {
			        box = document.getBoxObjectFor(el);
			        var borderLeft = (el.style.borderLeftWidth) ? parseInt(el.style.borderLeftWidth) : 0;
			        var borderTop = (el.style.borderTopWidth) ? parseInt(el.style.borderTopWidth) : 0;
			        pos = [box.x - borderLeft, box.y - borderTop];
			    }
			    else 
			    {
			        pos = [el.offsetLeft, el.offsetTop];
			        parent = el.offsetParent;
			        if (parent != el) {
			            while (parent) {
			                pos[0] += parent.offsetLeft;
			                pos[1] += parent.offsetTop;
			                parent = parent.offsetParent;
			            }
			        }
			        if (ua.indexOf('opera') != -1 || (ua.indexOf('safari') != -1 && el.style.position == 'absolute')) {
			            pos[0] -= document.body.offsetLeft;
			            pos[1] -= document.body.offsetTop;
			        }
			    }
			if (el.parentNode) {
			    parent = el.parentNode;
			}
			else {
			    parent = null;
			}
			while (parent && parent.tagName != 'BODY' && parent.tagName != 'HTML') { 
			    pos[0] -= parent.scrollLeft;
			    pos[1] -= parent.scrollTop;
			    if (parent.parentNode) {
			        parent = parent.parentNode;
			    }
			    else {
			        parent = null;
			    }
			}
			return {
			    x: pos[0],
			    y: pos[1]
			};
	     },
		 
	     setPos: function(x, y) { 
			this.each(function(els){
				els.style.position = "absolute";
				els.style.top = parseInt(y)+"px";
				els.style.left = parseInt(x)+"px";
			});
			return this;
	     },
		 
	     center: function() { 
			var x,y; 
			if (self.innerHeight) 
			{
				x = self.innerWidth; 
				y = self.innerHeight; 
			} 
			else if (document.documentElement && document.documentElement.clientHeight) 
			{
				x = document.documentElement.clientWidth; 
				y = document.documentElement.clientHeight; 
			} 
			else if (document.body) 
			{
				x = document.body.clientWidth; 
				y = document.body.clientHeight; 
			} 			
			var size = this.getSize();
			
			var top = (y - size.height)/2; 
			var left = (x - size.width)/2; 
			this.each(function(els){
				els.style.position = "absolute";
				els.style.top = parseInt(top)+"px";
				els.style.left = parseInt(left)+"px";
			});
			return this;
	     }		 
	}
	KUI.fn.init.prototype = KUI.fn;
	var counter = 0;
	KUI.getId = function(){
		return "KUI_" + (counter++);
	};
	
	/* 
	 * "mini" Selector Engine 
	 * Copyright (c) 2009 James Padolsey 
	 * ------------------------------------------------------- 
	 * Dual licensed under the MIT and GPL licenses. 
	 *    - http://www.opensource.org/licenses/mit-license.php 
	 *    - http://www.gnu.org/copyleft/gpl.html 
	 * ------------------------------------------------------- 
	 * Version: 0.01 (BETA) 
		
		Usage:
		
		var pAnchors = mini('p > a'); // Returns an array.
		
		for (var i = 0, l = pAnchors.length; i < l; ++i) {
		    // Do stuff...
		}
		Supported Selectors:
		
		tag 
		tag > .className 
		tag > tag 
		#id > tag.className 
		.className tag 
		tag, tag, #id 
		tag#id.className 
		.className 
		span > * > b 
	 */
	var mini=(function(){var b=/(?:[\w\-\\.#]+)+(?:\[\w+?=([\'"])?(?:\\\1|.)+?\1\])?|\*|>/ig,g=/^(?:[\w\-_]+)?\.([\w\-_]+)/,f=/^(?:[\w\-_]+)?#([\w\-_]+)/,j=/^([\w\*\-_]+)/,h=[null,null];function d(o,m){m=m||document;var k=/^[\w\-_#]+$/.test(o);if(!k&&m.querySelectorAll){return c(m.querySelectorAll(o))}if(o.indexOf(",")>-1){var v=o.split(/,/g),t=[],s=0,r=v.length;for(;s<r;++s){t=t.concat(d(v[s],m))}return e(t)}var p=o.match(b),n=p.pop(),l=(n.match(f)||h)[1],u=!l&&(n.match(g)||h)[1],w=!l&&(n.match(j)||h)[1],q;if(u&&!w&&m.getElementsByClassName){q=c(m.getElementsByClassName(u))}else{q=!l&&c(m.getElementsByTagName(w||"*"));if(u){q=i(q,"className",RegExp("(^|\\s)"+u+"(\\s|$)"))}if(l){var x=m.getElementById(l);return x?[x]:[]}}return p[0]&&q[0]?a(p,q):q}function c(o){try{return Array.prototype.slice.call(o)}catch(n){var l=[],m=0,k=o.length;for(;m<k;++m){l[m]=o[m]}return l}}function a(w,p,n){var q=w.pop();if(q===">"){return a(w,p,true)}var s=[],k=-1,l=(q.match(f)||h)[1],t=!l&&(q.match(g)||h)[1],v=!l&&(q.match(j)||h)[1],u=-1,m,x,o;v=v&&v.toLowerCase();while((m=p[++u])){x=m.parentNode;do{o=!v||v==="*"||v===x.nodeName.toLowerCase();o=o&&(!l||x.id===l);o=o&&(!t||RegExp("(^|\\s)"+t+"(\\s|$)").test(x.className));if(n||o){break}}while((x=x.parentNode));if(o){s[++k]=m}}return w[0]&&s[0]?a(w,s):s}var e=(function(){var k=+new Date();var l=(function(){var m=1;return function(p){var o=p.k,n=m++;if(!o){p.k=n;return true}return false}})();return function(m){var s=m.length,n=[],q=-1,o=0,p;for(;o<s;++o){p=m[o];if(l(p)){n[++q]=p}}k+=1;return n}})();function i(q,k,p){var m=-1,o,n=-1,l=[];while((o=q[++m])){if(p.test(o[k])){l[++n]=o}}return l}return d})();
	
})();

KUI.Browser = {
    Engine: {
        name: 'unknown',
        version: ''
    },
    Features: {
        xpath: !!(document.evaluate),
        air: !!(window.runtime)
    }
};

if (window.opera) 
	KUI.Browser.Engine = {
		name: 'presto',
		version: (document.getElementsByClassName) ? 950 : 925
	};
//IE
else 
	if (window.ActiveXObject) {
		KUI.Browser.Engine = {
			name: 'trident',
			version: (window.XMLHttpRequest) ? 5 : 4
		};
	}
	//Safari
	else 
		if (!navigator.taintEnabled) {
			KUI.Browser.Engine = {
				name: 'webkit',
				version: (KUI.Browser.Features.xpath) ? 420 : 419
			};
		}
		//Mozilla
		else {
			if (document.getBoxObjectFor != null) 
				KUI.Browser.Engine = {
					name: 'gecko',
					version: (document.getElementsByClassName) ? 19 : 18
				};
		}

KUI.Browser.Engine[KUI.Browser.Engine.name] = KUI.Browser.Engine[KUI.Browser.Engine.name + KUI.Browser.Engine.version] = true;
KUI.isIE = KUI.Browser.Engine.trident;
KUI.isOpera = KUI.Browser.Engine.presto;
KUI.isSafari = KUI.Browser.Engine.webkit;
KUI.isMozilla = KUI.Browser.Engine.gecko;

KUI.Class = {
    create: function(){
        return function(){
            this.initialize.apply(this, arguments);
        }
    }
};
KUI.extend = function(destination, source){
    for (var property in source) {
        destination[property] = source[property];
    }
    return destination;
};
KUI.bind = function(object, fun){
    return function(){
        return fun.apply(object, arguments);
    }
};


KUI.Event = new Array(), 
 KUI.Event.EventRouter = function(el, eventType){
    this.listeners = new Array();
    this.el = el;
    el.eventRouter = this;
    el[eventType] = KUI.Event.EventRouter.callback;
};
KUI.Event.EventRouter.callback = function(event){
    var e = event || window.event;
    var router = this.eventRouter;
    router.notify(e);
};
KUI.Event.EventRouter.prototype = {
    addListener: function(listener){
        this.listeners.add(listener, true);
    },
    
    removeListener: function(listener){
        this.listeners.remove(listener);
    },
    
    notify: function(e){
        var listeners = this.listeners;
        for (var i = 0; i < listeners.length; i++) {
            var listener = listeners[i];
            listener.call(this, e);
        }
    }
};

KUI.Event.bindAsEventListener = function(object, fun){
    return function(event){
        return fun.call(object, (event || window.event));
    }
};
KUI.Event.addEventHandler = function(oTarget, sEventType, fnHandler){
    if (oTarget.addEventListener) {
        oTarget.addEventListener(sEventType, fnHandler, false);
    }
    else 
        if (oTarget.attachEvent) {
            oTarget.attachEvent("on" + sEventType, fnHandler);
        }
        else {
            oTarget["on" + sEventType] = fnHandler;
        }
};

KUI.Event.removeEventHandler = function(oTarget, sEventType, fnHandler){
    if (oTarget.removeEventListener) {
        oTarget.removeEventListener(sEventType, fnHandler, false);
    }
    else 
        if (oTarget.detachEvent) {
            oTarget.detachEvent("on" + sEventType, fnHandler);
        }
        else {
            oTarget["on" + sEventType] = null;
        }
};

KUI.createElement = function(tagName){
    return document.createElementNS ? document.createElementNS("http://www.w3.org/1999/xhtml", tagName) : document.createElement(tagName);
};


KUI.createCanvas = function(w, h){
    var can = KUI.createElement("canvas");
    can.width = w;
    can.height = h;
    if (typeof G_vmlCanvasManager != "undefined") {
        G_vmlCanvasManager.initElement(can);
    }
    return can;
};

KUI.get = function(id){
    return "string" == typeof id ? document.getElementById(id) : id;
};

KUI.currentStyle = function(el){
    return el.style ? el.style : el.currentStyle ? el.currentStyle : window.getComputedStyle(el, null);
};

KUI.getDocSize = function(){
    var _Width = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
    var _Height = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
    return {
        width: Math.max(_Width, this.getViewportSize().width),
        height: Math.max(_Height, this.getViewportSize().height)
    };
};

KUI.getViewportSize = function(){
    return {
        width: window.innerWidth ? window.innerWidth : (document.documentElement && document.documentElement.clientWidth) ? document.documentElement.clientWidth : document.body.offsetWidth,
        height: window.innerHeight ? window.innerHeight : (document.documentElement && document.documentElement.clientHeight) ? document.documentElement.clientHeight : document.body.offsetHeight
    };
};

KUI.setAppPath = function(path){
    KUI.appPath = path;
}
KUI.getAppPath = function(path){
    if (!KUI.appPath) {
        alert('getAppPath failed!');
        return;
    }
    return KUI.appPath;
}

KUI.format = function(){
	var a = [].slice.apply(arguments);
	var s = a.shift();
    return s.replace(/\{[0-9]+\}/g, function(d){
        return a[d.slice(1, -1)];
    });
};

